from django.http import JsonResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
import datetime
from core.models.class_course import ClassCourse
from core.forms.class_course_form import ClassCourseForm
import json
from core.models.grade_schedule import GradeSchedule
from core.models.classinfo import ClassInfo
# 列表视图 - 显示所有课程
@csrf_exempt
def class_course_list(request):
    courses = ClassCourse.objects.all()
    return render(request, 'core/class_course_list.html', {'courses': courses})

# 创建视图 - 添加新课程
@csrf_exempt
def class_course_create(request):
    if request.method == 'POST':
        form = ClassCourseForm(request.POST)
        if form.is_valid():
            form.save()
            # 检查是否为AJAX请求
            if request.headers.get('x-requested-with') == 'XMLHttpRequest':
                return JsonResponse({'status': 'success'})
            return HttpResponseRedirect(reverse('core:class_course_list'))
        else:
            # 表单无效时返回错误信息
            if request.headers.get('x-requested-with') == 'XMLHttpRequest':
                return JsonResponse({'status': 'error', 'errors': form.errors}, status=400)
    else:
        form = ClassCourseForm()
    return render(request, 'core/class_course_form.html', {'form': form, 'title': '创建课程'})

# 详情视图 - 显示课程详情
@csrf_exempt
def class_course_detail(request, pk):
    course = get_object_or_404(ClassCourse, pk=pk)
    return render(request, 'core/class_course_detail.html', {'course': course})

# 更新视图 - 编辑课程
@csrf_exempt
def class_course_update(request, pk):
    course = get_object_or_404(ClassCourse, pk=pk)
    if request.method == 'POST':
        form = ClassCourseForm(request.POST, instance=course)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('core:class_course_list'))
    else:
        form = ClassCourseForm(instance=course)
    return render(request, 'core/class_course_form.html', {'form': form, 'title': '更新课程'})

# 删除视图 - 删除课程
@csrf_exempt
def class_course_delete(request, pk):
    course = get_object_or_404(ClassCourse, pk=pk)
    if request.method == 'POST':
        course.delete()
        return HttpResponseRedirect(reverse('core:class_course_list'))
    return render(request, 'core/class_course_confirm_delete.html', {'course': course})

@csrf_exempt
def get_class_course_detail(request, pk):
    try:
        course = ClassCourse.objects.get(pk=pk)
        data = {
            'id': course.id,
            'class_subject': course.class_subject.id,
            'weekday': course.weekday,
            'course_period': course.course_period.id if course.course_period else None
        }
        return JsonResponse(data)
    except ClassCourse.DoesNotExist:
        return JsonResponse({'error': '班级课程不存在'}, status=404)

@csrf_exempt
def class_course_update_ajax(request, pk):
    if request.method == 'POST':
        try:
            course = ClassCourse.objects.get(pk=pk)
            form = ClassCourseForm(request.POST, instance=course)
            if form.is_valid():
                form.save()
                return JsonResponse({'status': 'success'})
            else:
                return JsonResponse({'status': 'error', 'errors': form.errors}, status=400)
        except ClassCourse.DoesNotExist:
            return JsonResponse({'status': 'error', 'message': '班级课程不存在'}, status=404)
    return JsonResponse({'status': 'error', 'message': '无效的请求方法'}, status=405)

@csrf_exempt
def class_course_delete_ajax(request, pk):
    if request.method == 'POST':
        try:
            course = ClassCourse.objects.get(pk=pk)
            course.delete()
            return JsonResponse({'status': 'success'})
        except ClassCourse.DoesNotExist:
            return JsonResponse({'status': 'error', 'message': '班级课程不存在'}, status=404)
    return JsonResponse({'status': 'error', 'message': '无效的请求方法'}, status=405)

def get_grade_schedules(class_id):
    # 使用select_related优化查询，减少数据库访问
    grade = ClassInfo.objects.select_related('grade').get(pk=class_id).grade
    # 直接通过grade对象查询，而不是grade_id
    schedules = GradeSchedule.objects.filter(grade=grade)
    return schedules
    
@csrf_exempt
def get_course_by_classid(request,class_id):
    if not class_id:
        class_id = request.GET.get('class_id')
    schedules=get_grade_schedules(class_id)

    courses = ClassCourse.objects.filter(class_info_id=class_id)
    data = []
    today = timezone.now().date()
    # 计算当前日期所在周的周一
    monday = today - datetime.timedelta(days=today.weekday())

    for schedule in schedules:
        for course in courses:
            # 计算课程日期（基于周一和weekday）
            # 从date字段获取星期几（0-6，周一到周日），加1转换为1-7格式以匹配course.weekday
            if schedule.date.weekday() + 1 == course.weekday and schedule.is_class_day==1:
                course_date = schedule.date

                # 处理课程时间
                start_time = None
                end_time = None
                if course.course_period:
                    start_time = course.course_period.start_time
                    end_time = course.course_period.end_time

                # 构建完整的开始和结束时间字符串
                start_str = f"{course_date}T{start_time.strftime('%H:%M:%S')}" if start_time else f"{course_date}T00:00:00"
                end_str = f"{course_date}T{end_time.strftime('%H:%M:%S')}" if end_time else f"{course_date}T23:59:59"

                # 构建事件数据
                event = {
                    'id': str(course.id),
                    'title': course.class_subject.subject.name,
                    'start': start_str,
                    'end': end_str,
                    'allDay': False,
                    'backgroundColor': '#3788d8',
                    'borderColor': '#3788d8',
                    'textColor': '#ffffff',
                    'editable': True,
                    'source': {
                        'id': course.id,
                        'class_info_id': course.class_info.id,
                        'class_info_name': course.class_info.name,
                        'class_subject_id': course.class_subject.id,
                        'class_subject_name': f'{course.class_subject.class_id.name} - {course.class_subject.subject.name}',
                        'weekday': course.weekday,
                        'weekday_display': course.get_weekday_display(),
                        'course_period_id': course.course_period.id if course.course_period else None,
                        'course_period_name': course.course_period.name if course.course_period else '未知'
                    }
                }
                data.append(event)

    return JsonResponse(data, safe=False)
       



